package com.tiantian.quanminxiu.utils;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Looper;

import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.umeng.socialize.PlatformConfig;
import com.tiantian.quanminxiu.R;
import com.tiantian.quanminxiu.api.AnchorService;
import com.joanzapata.iconify.Iconify;
import com.joanzapata.iconify.fonts.FontAwesomeModule;
import com.joanzapata.iconify.fonts.IoniconsModule;
import com.shenglian.utils.utils.CommonUtils;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import rx.Scheduler;
import rx.schedulers.Schedulers;


public class ApplicationBase extends Application {

    public static final String Weixin_AppId = "wxe78c0a9d79733c17";
    public static final String Weixin_appSecret = "0a09777f4f838f091713b88b115fc897";
    public static final String QQ_AppId = "1106237397";
    public static final String QQ_appKey = "d3vppOUOVkvlF0QC";
    public static final String SinaWeibo_Key = "2063983377";
    public static final String SinaWeibo_appSecret = "af0c93b76c43bbcc77787250a79b367e";

    private List<Activity> list = new ArrayList<Activity>();
    private AnchorService anchorService;
    private Scheduler defaultSubscribeScheduler;

    public static String downAppUrl = "";

    //region onCreate
    @Override
    public void onCreate() {
        super.onCreate();

        Context context = getBaseContext();

        //错误异常处理
//        Thread.setDefaultUncaughtExceptionHandler(exceptionHandler);

        //初始化字图图标
        Iconify.with(new FontAwesomeModule()).with(new IoniconsModule());
        //初始化视图信息
        UserData.Current.Screen_Width = CommonUtils.getScreenWidth(context);
        UserData.Current.Screen_Height = CommonUtils.getScreenHeight(context);
        UserData.Current.APP_Version = CommonUtils.getVersionName(context);
        UserData.Current.APP_VersionCode = CommonUtils.getVersionCode(context);

        //ImageLoader初始化
        ImageLoader.getInstance().init(new ImageLoaderConfiguration
                .Builder(context)
                .memoryCache(new LruMemoryCache(2 * 1024 * 1024))
                .threadPoolSize(3)
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .diskCacheSize(50 * 1024 * 1024) // 50 MiB
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .defaultDisplayImageOptions(new DisplayImageOptions.Builder()
                        .showImageForEmptyUri(R.drawable.chat_common_empty_photo)//设置图片Uri为空或是错误的时候显示的图片
                        .displayer(new FadeInBitmapDisplayer(200))
                        .build())
                .build());

        try {
            UserData.Current.Equipment_Name = URLEncoder.encode(android.os.Build.BRAND + "_" + android.os.Build.MODEL, "gb2312");
            UserData.Current.OS_Version = android.os.Build.VERSION.RELEASE;
        } catch (Exception e) {
            e.printStackTrace();
        }

        PlatformConfig.setWeixin(Weixin_AppId, Weixin_appSecret);
        PlatformConfig.setSinaWeibo(SinaWeibo_Key, SinaWeibo_appSecret);
        PlatformConfig.setQQZone(QQ_AppId, QQ_appKey);

        downAppUrl = Constants.DOWN_APP +  APPUtils.getMetaInt(context,"UMENG_CHANNEL") ;
    }
    //endregion

    public static ApplicationBase get(Context context) {
        return (ApplicationBase) context.getApplicationContext();
    }

    public AnchorService getAnchorService() {
        if (anchorService == null) {
            anchorService = AnchorService.Factory.create();
        }
        return anchorService;
    }

    //For setting mocks during testing
    public void setAnchorService(AnchorService anchorService) {
        this.anchorService = anchorService;
    }

    public Scheduler defaultSubscribeScheduler() {
        if (defaultSubscribeScheduler == null) {
            defaultSubscribeScheduler = Schedulers.io();
        }
        return defaultSubscribeScheduler;
    }

    //User to change scheduler from tests
    public void setDefaultSubscribeScheduler(Scheduler scheduler) {
        this.defaultSubscribeScheduler = scheduler;
    }

    //region removeActivity Activity关闭时，删除Activity列表中的Activity对象
    public void removeActivity(Activity a) {
        list.remove(a);
    }
    //endregion

    //region addActivity 向Activity列表中添加Activity对象
    public void addActivity(Activity a) {
        list.add(a);
    }
    //endregion

    //region finishActivity 移除所有activity,结束进程
    public void finishActivity() {
        for (Activity activity : list) {
            if (null != activity) {
                activity.finish();
            }
        }
        //杀死该应用进程
        android.os.Process.killProcess(android.os.Process.myPid());
    }
    //endregion

/*    //region exceptionHandler 捕获异常，并重启程序
    private Thread.UncaughtExceptionHandler exceptionHandler = (thread, ex) -> {
        Thread.UncaughtExceptionHandler mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        if (!handleException(ex) && mDefaultHandler != null) {
            //如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, ex);
        } else {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Intent intent = new Intent(getApplicationContext(), Activity_Init.class);
            PendingIntent restartIntent = PendingIntent.getActivity(
                    getApplicationContext(), 0, intent,
                    Intent.FLAG_ACTIVITY_NEW_TASK);
            //退出程序
            AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            mgr.set(AlarmManager.RTC, System.currentTimeMillis(),
                    restartIntent); // 1秒钟后重启应用
            finishActivity();
        }
    };*/
    //endregion

    //region handleException 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.  @param ex  @return true:如果处理了该异常信息;否则返回false.
    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }
        //使用Toast来显示异常信息
        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                CommonUtils.showToask(getApplicationContext(), "很抱歉,程序出现异常,即将重新启动.");
                Looper.loop();
            }
        }.start();
        return true;
    }
    //endregion
}